// pages/goods_detail/goods_detail.js
import { request } from "../../request/request"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    // goods_introduce: null
  },

  GoodsDetail: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { goods_id } = options;
    this.getGoodsDetail(goods_id)
  },


  getGoodsDetail(goods_id) {
    request({ url: "/goods/detail", data: { goods_id } }).then(res => {
      this.GoodsDetail = res.data.message;
      const goodsObj = res.data.message;
      this.setData({
        // goods_introduce: goodsObj.goods_introduce.request(/\.webp/g, '.jpg'),
        goodsObj
      })
    })
  },
  prevviewImageClick(e) {
    const current = e.currentTarget.dataset.url;
    const urls = this.GoodsDetail.pics.map(v => v.pics_mid)
    wx.previewImage({
      current, // 当前显示图片的http链接
      urls// 需要预览的图片http链接列表
    })
  },

  // 加入购物车
  handelCartAdd() {
    // 1 获取缓存，如果没有设置数组
    const cart = wx.getStorageSync('cart') || [];
    // 2 判断商城是否存在购物车数组中
    const index = cart.findIndex(v => v.goods_id === this.GoodsDetail.goods_id);
    if (index === -1) {
      // 不存在 num+1
      this.GoodsDetail.num = 1;
      this.GoodsDetail.checked = true;
      cart.push(this.GoodsDetail)
    } else {
      cart[index].num++;
    }
    wx.setStorage({
      data: cart,
      key: 'cart',
    })
    wx.showToast({
      title: '加入成功',
      icon: "success",
      mask: true
    })
  }
})